package com.padgett.resourcemanagement.listener;

import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * Initialize invoice number.
 * 
 * @author andyleung
 * 
 */
public class InvoiceServletContext implements ServletContextListener{
	private static final Logger logger=Logger.getLogger(InvoiceServletContext.class.getName());
	public static final int INVOICE_START_NUMBER=9000;
	public static final int INCREMENT=1000;
	public static final double HST=0.13;
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		/*
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query=new Query("InvoiceNumber");
		PreparedQuery preparedQuery=datastore.prepare(query);
		int numInvoice=preparedQuery.countEntities(FetchOptions.Builder.withDefaults());
		if(numInvoice==0){
			// Generate 1000 from default start number.
			List<Entity> newInvoiceNumbers=new ArrayList<Entity>();
			int max=InvoiceServletContext.INVOICE_START_NUMBER+InvoiceServletContext.INCREMENT;
			for(int i=INVOICE_START_NUMBER;i<max;i++){
				Entity invoiceNumber=new Entity("InvoiceNumber",i);
				invoiceNumber.setProperty("Number",i);
				invoiceNumber.setProperty("Used",false);
				newInvoiceNumbers.add(invoiceNumber);
			}
			datastore.put(newInvoiceNumbers);
		}else if(numInvoice<1000){
			// Generate another 1000 from last "unused".
			query=new Query("InvoiceNumber")
			.setFilter(new Query.FilterPredicate("Used",Query.FilterOperator.EQUAL,Boolean.FALSE)).addSort("Number", SortDirection.DESCENDING);
			preparedQuery=datastore.prepare(query);
			List<Entity> entities=preparedQuery.asList(FetchOptions.Builder.withLimit(1));
			Entity lastInvoice=entities.get(0);
			int lastUnusedNumber=((Long)lastInvoice.getProperty("Number")).intValue();
			lastUnusedNumber++;// For next start
			List<Entity> newInvoiceNumbers=new ArrayList<Entity>();
			int max=lastUnusedNumber+InvoiceServletContext.INCREMENT;
			for(int i=lastUnusedNumber;i<max;i++){
				Entity invoiceNumber=new Entity("InvoiceNumber",i);
				invoiceNumber.setProperty("Number",i);
				invoiceNumber.setProperty("Used",false);
				newInvoiceNumbers.add(invoiceNumber);
			}
			datastore.put(newInvoiceNumbers);
		}
	*/
	}
}
